<!--
 * @Author: HeAo
 * @Date: 2021-09-29 14:54:05
 * @LastEditTime: 2021-09-29 15:25:10
 * @LastEditors: HeAo
 * @Description: 
 * @FilePath: \web2103-2105\web2105\3-1-ES6\day05\3-promise-封装.html
 * 别乱动！
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>promise封装</title>
  <script src="./jquery.js"></script>
  <script>
    const baseUrl = 'http://47.94.46.113:8888'

    // 封装获取promise实例的工厂函数
    function getPromise(url, method) {
      return new Promise((resolve, reject) => {
        $.ajax({
          url: baseUrl + url,
          method,
          success(res) {
            resolve(res)
          },
          error(err) {
            reject(err)
          }
        })
      })
    }

    // 调用工厂函数，获取promise实例
    let pro1 = getPromise('/index/category/findAll', 'get')
    let pro2 = getPromise('/index/carousel/findAll', 'get')

    // let pro3 = Promise.all([pro1, pro2])
    // let pro3 = Promise.any([pro1, pro2])
    // let pro3 = Promise.race([pro1, pro2])

    // pro3.then(res => {
    //   console.log('成功', res.data[0]);
    // }).catch(err => {
    //   console.log('错误', err);
    // })






    // 通过调用promise实例方法，来访问其内部的状态
    // pro1.then(res => {
    //   console.log(res);
    // }).catch(err => {
    //   console.log(err);
    // }).finally(() => {
    //   console.log('结束了');
    // })

    // pro2.then(res => {
    //   console.log(res);
    // }).catch(err => {
    //   console.log(err);
    // })

    let obj1 = {
      name: 'zhangsan',
      age: 12,
      gender: 'male'
    }
    let obj2 = {
      status: 500,
      message: '后台接口异常',
      data: 'null',
      timestamp: new Date().getTime()
    }

    let pro3 = Promise.resolve(obj1);
    let pro4 = Promise.reject(obj2);

    // console.log(pro3);
    // pro3.then(data => {
    //   console.log(data);
    // })

    console.log(pro4);
    pro4.catch(err => {
      console.log(err);
    })

  </script>
</head>

<body>

</body>

</html>